package edu.zut.cs.software.example.Login.web.spring.controller;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import edu.zut.cs.software.example.student.dao.StudentDao;
import edu.zut.cs.software.example.student.domain.Student;
import edu.zut.cs.software.example.student.service.StudentManager;
import edu.zut.cs.software.example.util.JWT.JwtHelper;


/**
 * The login
 * @author chen ming yang
 *
 */
@RestController
public class LoginController {

	@Autowired
	StudentManager studentManager;

	@RequestMapping("/login")
	public String login(@RequestBody Student student,HttpServletRequest request) {
		String flag ="error";
		String token = null;
		Student stu = null;

		String ACtoken = request.getHeader("Authorization");

		if(ACtoken.length()==4) {
			//如果前端发送的ACtoken是空的，说明是第一次登陆，那就先去找用户存在不
			stu = studentManager.loginService(student);
			if (stu!=null) {
				//如果用户存在就签发token
				flag="ok";
				token=JwtHelper.createToken(student.getUserId());
			}
		}else {
			//如果前端发送的ACtoken不是空的，那就去调用jwt解析器去解析验证
			JwtHelper.parseToken(ACtoken);
		}
	
		
		
		HashMap<String,Object> res=new HashMap<String, Object>();//放入map集合K:V
		res.put("flag", flag);//收容标记flag 前是字符串后是字符串对象定义的hashmap
		res.put("token",token);
		String res_json=JSON.toJSONString(res);//把一个对象转换为json串:把收容有flag标记和student对象转变成json数据

		return res_json;//含有两块信息回应给前端
	}
}
